
import React, { useMemo } from 'react';
import type { TransactionRead } from '../types';
import Card from './ui/Card';

interface TodaysSpendingProps {
  transactions: TransactionRead[];
  currencyCode: string;
}

const TodaysSpending: React.FC<TodaysSpendingProps> = ({ transactions, currencyCode }) => {
  const { totalSpending, count } = useMemo(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0); // Start of today
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1); // Start of tomorrow

    let total = 0;
    let transactionCount = 0;

    transactions.forEach(tx => {
      tx.attributes.transactions.forEach(split => {
        const transactionDate = new Date(split.date);
        if (
          split.type === 'withdrawal' &&
          transactionDate >= today &&
          transactionDate < tomorrow
        ) {
          total += parseFloat(split.amount);
          transactionCount++;
        }
      });
    });

    return { totalSpending: total, count: transactionCount };
  }, [transactions]);

  const formattedSpending = new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: currencyCode,
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(totalSpending);

  return (
    <section>
      <h2 className="text-lg font-semibold text-slate-300 mb-3">今日支出</h2>
      <Card className="flex items-center justify-between p-5 bg-slate-800/70">
        <div className="flex items-center">
          <div className="flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center bg-orange-500/20 text-orange-400">
             <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-6 h-6">
               <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
             </svg>
          </div>
          <div className="ml-4">
            <p className="text-2xl font-bold text-white tracking-tight">{formattedSpending}</p>
          </div>
        </div>
        <div className="text-right">
           {count > 0 ? (
                <p className="text-sm text-slate-400">
                    基于 <span className="font-semibold text-white">{count}</span> 笔交易
                </p>
            ) : (
                <p className="text-sm text-slate-500">今日无支出</p>
            )}
        </div>
      </Card>
    </section>
  );
};

export default TodaysSpending;
